package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Collection;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointCut() {}

    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) {
        log.info("开始进行公共字段自动填充...");

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType operationType = autoFill.value();

        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return;
        }

        Object entity = args[0];
        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();

        try {
            if (entity instanceof Collection) {
                for (Object element : (Collection<?>) entity) {
                    fillFields(element, operationType, now, currentId);
                }
            } else {
                fillFields(entity, operationType, now, currentId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void fillFields(Object entity, OperationType operationType, LocalDateTime now, Long currentId) throws Exception {
        if (operationType == OperationType.INSERT) {
            setField(entity, AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class, now);
            setField(entity, AutoFillConstant.SET_CREATE_USER, Long.class, currentId);
            setField(entity, AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class, now);
            setField(entity, AutoFillConstant.SET_UPDATE_USER, Long.class, currentId);
        } else if (operationType == OperationType.UPDATE) {
            setField(entity, AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class, now);
            setField(entity, AutoFillConstant.SET_UPDATE_USER, Long.class, currentId);
        }
    }

    private void setField(Object entity, String methodName, Class<?> parameterType, Object value) {
        try {
            Method method = entity.getClass().getDeclaredMethod(methodName, parameterType);
            method.invoke(entity, value);
        } catch (NoSuchMethodException e) {
            log.warn("Method {} not found in class {}", methodName, entity.getClass().getName());
        } catch (Exception e) {
            log.error("Error setting field {}: {}", methodName, e.getMessage());
        }
    }
}
